﻿#include "ISqlite.h"
#include <QDebug>
#include <QThread>
#include <QSqlQuery>
#include <QProcess>
#include <QSqlError>

ISqlite::ISqlite(QObject *parent) : IDatabase(parent)
{

}

ISqlite::ISqlite(const SqlLinkParam &par, QObject *parent):IDatabase(par, parent)
{
}

bool ISqlite::init()
{
    if(connect()){
        setSqlState(SS_Valid);
        if(!createTable()){
            setSqlError(SE_CreateTB);
            mErrMsg = mDb.lastError().text();
            return false;
        }
    } else {
        setSqlState(SS_Invalid);
        return false;
    }
    return true;
}


bool ISqlite::connect()
{
    mDb = QSqlDatabase::addDatabase("QSQLITE", mLinkPar.linkName);
    mDb.setHostName(mLinkPar.ip);
    mDb.setPort(mLinkPar.port);
    mDb.setUserName(mLinkPar.user);
    mDb.setPassword(mLinkPar.password);
    mDb.setDatabaseName(mLinkPar.dbName + ".db");
    if(!mDb.open()){
        qDebug() << "fail to open mysql:" + mDb.lastError().text();
        return false;
    }
    return true;
}


bool ISqlite::createTable()
{
    QSqlQuery query(mDb);
    QString sqlStatement = QString("CREATE TABLE IF NOT EXISTS %1 "
                                   "(%2 varchar(256) primary key, "
                                   "%3 varchar(30), "
                                   "%4 varchar(30), "
                                   "%5 text not null)").arg(mLinkPar.tableName,
                                    DBUuid, DBCreatTime, DBModifyTime, DBJson);
    if(!query.exec(sqlStatement)){
        qDebug() << query.lastError().text() << sqlStatement;
        return false;
    }
    return false;
}

